package com.rookie.im.server.utils;

import com.rookie.im.server.config.AppConfig;
import lombok.Getter;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;

public class RedisManager {

    @Getter
    private static volatile RedissonClient redissonClient;
    private static final Object lock = new Object();

    public static void init(AppConfig.RedisConfig redisConfig) {
        if (redissonClient == null) {
            synchronized (lock) {
                if (redissonClient == null) {
                    redissonClient = getRedissonClient(redisConfig);
                }
            }
        }
    }

    public static RedissonClient getRedissonClient(AppConfig.RedisConfig redisConfig) {
        Config config = new Config();
        String node = redisConfig.getSingle().getAddress();
        node = node.startsWith("redis://") ? node : "redis://" + node;
        SingleServerConfig singleServerConfig = config.useSingleServer()
                .setAddress(node)
                .setDatabase(redisConfig.getDatabase())
                .setTimeout(redisConfig.getTimeout())
                .setConnectTimeout(redisConfig.getPoolConnTimeout())
                .setConnectionMinimumIdleSize(redisConfig.getPoolMinIdle())
                .setConnectionPoolSize(redisConfig.getPoolSize());
        if (redisConfig.getPassword() != null && !redisConfig.getPassword().isEmpty()) {
            singleServerConfig.setPassword(redisConfig.getPassword());
        }
        config.setCodec(new StringCodec());
        return Redisson.create(config);
    }
}
